/**
 * Activity服务类
 * @author yanwl
 * @date 2017-01-22 03:56:28
*/
package com.company.example.service.impl;

import com.company.example.core.common.DaoHelperTest;
import com.company.example.model.pojo.Activity;
import com.company.example.service.ActivityService;
import com.company.example.task.ActivitySchedule;
import com.company.example.utils.Constants;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Service
public class ActivityServiceImpl extends BaseServiceImpl<Activity, Integer> implements ActivityService{
    private static ScheduledExecutorService executor;

    static {
        executor = new ScheduledThreadPoolExecutor(10);
    }

    @Override
    public List<Activity> findUnEndActivities() {
        return (List<Activity>)DaoHelperTest.list(super.getNameSpace(),"selectUnEndActivities",null);
    }

    @Override
    public List<ScheduledFuture> findScheduledList(Activity activity) {
        List<ScheduledFuture> scheduledFutures = new ArrayList<ScheduledFuture>();
        if(Constants.ACTIVITY_STATUS_UNSTARTED == activity.getActivityStatus()) {
            // 自动开始定时
            ScheduledFuture autoActivityStart = autoActivityStart(activity);
            if(autoActivityStart != null) {
                scheduledFutures.add(autoActivityStart);
            }
            // 自动结束定时
            ScheduledFuture autoActivityEnd = autoActivityEnd(activity);
            if(autoActivityEnd != null) {
                scheduledFutures.add(autoActivityEnd);
            }
        }else if(Constants.ACTIVITY_STATUS_WORK == activity.getActivityStatus() || Constants.ACTIVITY_STATUS_STOP == activity.getActivityStatus()) {
            // 自动结束定时
            ScheduledFuture autoActivityEnd = autoActivityEnd(activity);
            if(autoActivityEnd != null) {
                scheduledFutures.add(autoActivityEnd);
            }
        }
        return scheduledFutures;
    }

    // 活动自动开始
    public ScheduledFuture autoActivityStart(Activity activity) {
        Date startTime = activity.getStartTime();
        if(startTime == null) {
            return null;
        }
        long delay = startTime.getTime() - System.currentTimeMillis();
        if(delay < 0) {
            // 直接更新活动状态为开始
            activity.setActivityStatus(Constants.ACTIVITY_STATUS_WORK);
            update(activity);
            return null;
        }
        return executor.schedule(new Runnable() {
            @Override
            public void run() {
                try {
                    activity.setActivityStatus(Constants.ACTIVITY_STATUS_WORK);
                    update(activity);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, delay, TimeUnit.MILLISECONDS);
    }

    // 活动自动结束
    public ScheduledFuture autoActivityEnd(Activity activity) {
        Date endTime = activity.getEndTime();
        if(endTime == null) {
            return null;
        }
        long delay = endTime.getTime() - System.currentTimeMillis();
        if(delay < 0) {
            // 直接更新活动状态为结束
            activity.setActivityStatus(Constants.ACTIVITY_STATUS_FINISH);
            update(activity);
            return null;
        }
        return executor.schedule(new Runnable() {
            @Override
            public void run() {
                try {
                    activity.setActivityStatus(Constants.ACTIVITY_STATUS_FINISH);
                    update(activity);
                    ActivitySchedule.getActivitiesMap().remove(activity.getId());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, delay, TimeUnit.MILLISECONDS);
    }

    // 定时任务的取消
    public void cancelScheduledFuture(ScheduledFuture scheduledFuture){
        // cancel参数为true时，正在执行的ScheduledFuture也会停止执行，参数为false时，正在执行的ScheduledFuture会执行完毕
        scheduledFuture.cancel(false);
    }

    @Override
    public boolean deleteActivity(Activity activity) {
        final Integer id = activity.getId();
        List<ScheduledFuture> scheduledFutures = ActivitySchedule.getActivitiesMap().get(id);
        if(!CollectionUtils.isEmpty(scheduledFutures)) {
            for (ScheduledFuture scheduledFuture : scheduledFutures) {
                cancelScheduledFuture(scheduledFuture);
            }
            ActivitySchedule.getActivitiesMap().remove(id);
        }
        return delete(id);
    }

    @Override
    public Integer insertActivity(Activity activity) {
        boolean isSuccess = insert(activity);
        if(isSuccess) {
            ActivitySchedule.getActivitiesMap().put(activity.getId(),findScheduledList(activity));
            return activity.getId();
        }
        return 0;
    }
}